package com.example.DemoDataeaseExample.provider;

import com.example.DemoDataeaseExample.entity.ConnectionObj;
import com.example.DemoDataeaseExample.entity.DatasourceConfiguration;
import com.example.DemoDataeaseExample.entity.DatasourceDTO;
import com.example.DemoDataeaseExample.entity.DatasourceSchemaDTO;
import org.apache.calcite.config.Lex;
import org.apache.calcite.sql.SqlDialect;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.dialect.PostgresqlSqlDialect;
import org.apache.calcite.sql.parser.SqlParseException;
import org.apache.calcite.sql.parser.SqlParser;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

public abstract class Provider {

    // 获取数据库连接
    public abstract ConnectionObj getConnection(DatasourceDTO datasource) throws Exception;

    // 检查连接状态
    public abstract String checkStatus(DatasourceDTO datasource) throws Exception;


    // 获取通用Statement
    public Statement getStatement(Connection connection, int queryTimeout) {
        if (connection == null) {
            throw new RuntimeException("连接为空");
        }

        Statement stmt = null;
        try {
            stmt = connection.createStatement();
            stmt.setQueryTimeout(queryTimeout);
        } catch (SQLException e) {
            throw new RuntimeException("创建Statement失败: " + e.getMessage());
        }
        return stmt;
    }

    public SqlDialect getDialect(DatasourceSchemaDTO coreDatasource) {
        SqlDialect sqlDialect;
        DatasourceConfiguration.DatasourceType datasourceType = DatasourceConfiguration.DatasourceType.valueOf(coreDatasource.getType());

        switch (datasourceType) {
            case kingbase:
                //人大金仓使用PostgreSQL的Dialect
                sqlDialect = PostgresqlSqlDialect.DEFAULT;
                break;

            default:
                sqlDialect = PostgresqlSqlDialect.DEFAULT;
                break;
        }
        return sqlDialect;
    }

    public String transSqlDialect(String sql, Map<Long, DatasourceSchemaDTO> dsMap) {
        DatasourceSchemaDTO value = dsMap.entrySet().iterator().next().getValue();
        try {
            // 关键点1：这里必须使用 SqlParser.Config.DEFAULT.withLex(Lex.JAVA)
            SqlParser parser = SqlParser.create(sql, SqlParser.Config.DEFAULT.withLex(Lex.JAVA));
            SqlNode sqlNode = parser.parseStmt();
            return sqlNode.toSqlString(getDialect(value)).toString();
        } catch (SqlParseException e) {
            throw new RuntimeException("SQL方言转换失败：" + e.getMessage());
        }
    }



}